package com.my.listener;

import com.alibaba.fastjson2.JSON;
import com.my.constants.MessageRabbitConstants;
import com.my.dto.MessageDTO;
import com.my.service.MessageService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author : jhxue
 * @create_time : 2023/11/7 9:02
 * @Description AI瑕疵检测数据监听器
 */
@Slf4j
@Component
public class WecomMsgListener {

    @Autowired
    private MessageService messageService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = MessageRabbitConstants.WECOM_MSG_QUEUE_NAME),
                    exchange = @Exchange(name = MessageRabbitConstants.WECOM_MSG_EXCHANGE_NAME),
                    key = MessageRabbitConstants.WECOM_MSG_ROUTE_KEY
            ),
            ackMode = "MANUAL"
    )
    public void listenMsg(Message message, String msg, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.info("接收数据:{}", msg);

        try {
            MessageDTO messageDTO = JSON.parseObject(msg, MessageDTO.class);
            messageService.receiveMsg(messageDTO);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("接收失败", e);
            channel.basicNack(deliveryTag, false, false);
        }
    }
}
